<template>
  <div class="app-container">
    <div style="font-size: 25px;">发货出库</div>
    <el-divider></el-divider>
    <el-form ref="form" :model="form" :rules="rules" label-width="80px">
      <el-col :span="8">
        <el-form-item label="销售单号" prop="saleNumber" style="width: 400px"
                      :rules="[{ required: true ,message: '请输入销售单号'}]">
          <el-input v-model="form.saleNumber" placeholder="请输入销售单号" maxlength="15" required="required" disabled/>
        </el-form-item>
      </el-col>
      <el-col :span="8">
        <el-form-item label="客户" prop="customerId" style="width: 400px" :rules="[{ required: true ,message: '请选择客户'}]">
          <el-select
            disabled
            v-model="form.customerId"
            placeholder="请选择客户"
            clearable
            size="small"
            style="width: 100%"
            @change="getInfo(form.customerId)"
          >
            <el-option
              v-for="dict in customerList"
              :key="dict.id"
              :label="dict.name"
              :value="dict.id"
            />
          </el-select>
        </el-form-item>
      </el-col>
      <el-col :span="8">
        <el-form-item label="客户手机" style="width: 400px" prop="customerPhone">
          <el-input disabled v-model="customerTelephone" placeholder="请输入客户手机"/>
        </el-form-item>
      </el-col>
      <el-col :span="8">
        <el-form-item label="收获地址" style="width: 400px" prop="customerAddress">
          <el-cascader
            disabled
            style="width: 100%"
            expand-trigger="hover"
            ref="cascaderAddr"
            size="small"
            :options="options"
            v-model="selectedOptions"
            @change="handleChange">
            <template slot-scope="{ node, data }">
              <span>{{ data.label }}</span>
              <span v-if="!node.isLeaf"> ({{ data.children.length }}) </span>
            </template>
          </el-cascader>
        </el-form-item>
      </el-col>
      <el-col :span="8">
        <el-form-item label="详细地址" style="width: 400px" prop="detailedAddress">
          <el-input v-model="detailedAdd" disabled placeholder="请输入详细地址"/>
        </el-form-item>
      </el-col>
      <el-col :span="8">
        <el-form-item label="固定电话" style="width: 400px" prop="fixedTelephone">
          <el-input v-model="form.fixedTelephone" disabled placeholder="请输入固定电话"/>
        </el-form-item>
      </el-col>
      <el-col :span="8">
        <el-form-item label="收款方式" style="width: 400px" prop="paymentMethod">
          <el-select v-model="form.paymentMethod" disabled placeholder="请选择收款方式" style="width: 100%" clearable>
            <el-option
              v-for="dict in dict.type.erp_payment_type"
              :key="dict.value"
              :label="dict.label"
              :value="parseInt(dict.value)"
            ></el-option>
          </el-select>
        </el-form-item>
      </el-col>
      <el-col :span="8">
        <el-form-item label="备注" style="width: 400px" prop="customerContact">
          <el-input v-model="form.customerContact" disabled placeholder="请输入简要备注" maxlength="255"/>
        </el-form-item>
      </el-col>
      <el-row>
        <el-col :span="8">
          <el-form-item label="发货单号" style="width: 400px" prop="shipmentNum">
            <el-input v-model="shipmentNo"
                      placeholder="发货单号"
                      maxlength="15"
                      :disabled="shipmentNoType"/>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="8">
          <el-form-item label="订单状态" style="width: 400px">
            <span style="display:inline-block;width:200px;font-weight:bold;">
            {{ auditStatus }}
          </span>
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>
    <el-row>
      <el-table :data="addGoodsList" default-expand-all show-summary :summary-method="getSummaries"
                :row-class-name="getRowClassName" :close-on-click-modal = "false">
        <el-table-column type="expand">
          <template slot-scope="props">
            <el-table v-show="props.row.goodWarehouseList.length != 0" v-bind:data="props.row.goodWarehouseList"
                      :default-expand-all="true" show-summary :summary-method="getSummaries" :show-header="true"
                      :header-cell-style="{background:'#FFFFFF',color:'#606266'}">
              <el-table-column prop="warehouseName" align="center" label="发货仓库"/>
              <el-table-column prop="goodsNumber" align="center" label="发货数量"/>
            </el-table>
          </template>
        </el-table-column>
        <el-table-column label="商品ID" align="center" prop="id"/>
        <el-table-column label="商品名称" align="center" prop="name"/>
        <el-table-column label="分类" align="center" prop="categoryName"/>
        <el-table-column label="品牌" align="center" prop="brandName"/>
        <el-table-column label="单位" align="center" prop="companyName"/>
        <el-table-column label="成本单价" align="center" prop="cost"/>
        <el-table-column label="销售单价" align="center" prop="price">
          <div class="item" slot-scope="scope">
            <el-input disabled v-model="scope.row.price" placeholder="请输入价格" size="mini"
                      @keyup.native="scope.row.price = scope.row.price = scope.row.price.replace(/[^\d.]/g,'');
                                   scope.row.price = scope.row.price.replace(/\.{2,}/g,'.');
                                   scope.row.price = scope.row.price.replace(/^\./g,'');
                                   scope.row.price = scope.row.price.replace('.','$#$').replace(/\./g,'').replace('$#$','.');
                                   scope.row.price = scope.row.price.replace(/^(\-)*(\d+)\.(\d\d).*$/,'$1$2.$3');"
                      style="width:100px" @input="handleEdit(scope.$index, scope.row)"></el-input>
          </div>
        </el-table-column>
        <el-table-column label="销售数量" align="center" prop="quantity">
          <div class="item" slot-scope="scope">
            <el-input-number v-model="scope.row.quantity" disabled controls-position="right" :min="1" size="mini"
                             style="width:100px" @input="handleEdit(scope.$index, scope.row)"/>
          </div>
        </el-table-column>
        <el-table-column label="销售总价" align="center" prop="oneGoodPrice">
          <div class="item" slot-scope="scope">
            <el-input disabled v-model="scope.row.oneGoodPrice" placeholder="销售总价" size="mini"
                      style="width:100px" readonly="readonly"></el-input>
          </div>
        </el-table-column>
        <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
          <template slot-scope="scope">
            <el-button
              size="mini"
              v-show="scope.row.goodWarehouseList.length === 0"
              type="text"
              icon="el-icon-edit"
              @click="choiceWarehouse(scope.row)"
              v-hasPermi="['system:goods:edit']"
            >发货仓库
            </el-button>
            <el-button
              size="mini"
              v-show="scope.row.goodWarehouseList.length != 0"
              type="text"
              icon="el-icon-edit"
              v-if="saleType"
              @click="updateWarehouse(scope.row)"
              v-hasPermi="['system:goods:edit']"
            >修改
            </el-button>
          </template>
        </el-table-column>
      </el-table>
    </el-row>
    <div slot="footer" class="dialog-footer" style="text-align:center;margin-top: 20px;">
      <el-button type="primary" @click="deliveryIssue(2)" v-if="saleType">发货出库</el-button>
    </div>
    <!--新增销售商品发货仓库弹出框 -->
    <el-dialog :title="title" :visible.sync="open" width="1500px" append-to-body :close-on-click-modal="false">
      <div>
        <span></span>
      </div>
      <el-table v-loading="loading" :data="warehouseGoodsList">
        <el-table-column label="商品ID" align="center" prop="goodId"/>
        <el-table-column label="商品名称" align="center" prop="goodName"/>
        <el-table-column label="仓库名称" align="center" prop="warehouseName"/>
        <el-table-column label="仓库商品库存" align="center" prop="goodsNumber"/>
        <el-table-column label="仓库发货数量" align="center" prop="goodSaleWarehouse">
          <div class="item" slot-scope="scope">
            <el-input-number v-model="scope.row.goodSaleWarehouse" controls-position="right" :min="0" size="mini"
                             style="width:100px"/>
          </div>
        </el-table-column>
      </el-table>
      <div slot="footer" class="dialog-footer" style="text-align:center;margin-top: 20px;">
        <el-button type="primary" @click="addGoodsDeliveryWarehouse">确 定</el-button>
      </div>
    </el-dialog>
    <!--修改销售商品发货仓库弹出框 -->
    <el-dialog :title="title" :visible.sync="updateOpen" width="1500px" append-to-body :close-on-click-modal="false">
      <el-table v-loading="loading" :data="updateWarehouseGoodsList">
        <el-table-column label="商品ID" align="center" prop="goodId"/>
        <el-table-column label="商品名称" align="center" prop="goodName"/>
        <el-table-column label="仓库名称" align="center" prop="warehouseName"/>
        <el-table-column label="仓库商品库存" align="center" prop="goodsNumber"/>
        <el-table-column label="仓库发货数量" align="center" prop="goodSaleWarehouse">
          <div class="item" slot-scope="scope">
            <el-input-number v-model="scope.row.goodSaleWarehouse" controls-position="right" :min="0" size="mini"
                             style="width:100px"/>
          </div>
        </el-table-column>
      </el-table>
      <div slot="footer" class="dialog-footer" style="text-align:center;margin-top: 20px;">
        <el-button type="primary" @click="UGoodsSaleWarehouseNum">确 定</el-button>
      </div>

    </el-dialog>
  </div>

</template>

<script>

import {getCustomer, listCustomer} from "@/api/erp/customer";
import {CodeToText, regionData} from "element-china-area-data";
import {listCategory} from "@/api/erp/category";
import {listBrand} from "@/api/erp/brand";
import Treeselect from "@riophae/vue-treeselect";
import "@riophae/vue-treeselect/dist/vue-treeselect.css";
import {addGoodsSaleWarehouse, checkGoodsSaleWarehouse, ConfirmDeliveryQuantity, getSale, updateSaleType, upGoodsSaleWarehouse} from "@/api/erp/sale";
import {getWarehouse, getWarehouseBySaleId} from "@/api/erp/goodsWarehouse";

let stream = require('stream')

export default {
  name: "sale",
  components: {Treeselect},
  dicts: ['erp_payment_type'],
  data() {
    return {
      //发货单号
      shipmentNo: null,
      //发货单号状态
      shipmentNoType: null,
      //订单状态
      auditStatus: null,
      //修改商品各个仓库库存数据列表
      updateWarehouseGoodsList: [],
      //新增商品各个仓库库存数据列表
      warehouseGoodsList: [],
      //发货按钮显示状态
      saleType: false,
      //销售id
      sellId: null,
      //品牌列表
      brandList: [],
      //elementUi地区数据
      options: regionData,
      //分类列表
      categoryOptions: [],
      //客户列表
      customerList: [],
      //客户电话
      customerTelephone: null,
      //客户地址
      detailedAdd: null,
      // 商品信息表格数据
      goodsList: [],
      //添加的商品信息表格数据
      addGoodsList: [],
      //客户省市区
      selectedOptions: [],
      //表单参数
      form: {},
      //商品表单参数
      goodsForm: {},
      // 显示搜索条件
      showSearch: true,
      // 遮罩层
      loading: true,
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 修改是否显示弹出层
      updateOpen: false,
      //表单校验
      rules: {},
    };
  },
  created() {
    const saleId = this.$route.query.id
    this.sellId = saleId;
    if (saleId) {
      this.getList(saleId);
    }
    this.selectCustomer();
  },

  methods: {
    //刷新页面数据
    getList(saleId) {
      var _that = this
      getSale(saleId).then(response => {
        this.form = response.data
        this.customerTelephone = response.data.customerPhone
        this.detailedAdd = response.data.detailedAddress
        this.selectedOptions = [response.data.province.toString(), response.data.city.toString(), response.data.area.toString()]
        this.addGoodsList = response.data.goodsList;
        if (response.data.shipmentNum != undefined) {
          this.shipmentNo = response.data.shipmentNum
        } else {
          _that.getCurrentTime();
        }
        if (response.data.type == 0) {
          this.saleType = true
          this.auditStatus = "已确认"
        }
        if (response.data.type == 2) {
          this.saleType = false
          this.auditStatus = "已发货"
          this.shipmentNoType = true
        }
      })
    },
    //发货出库按钮操作
    deliveryIssue(type) {
      let id = this.sellId;
      let num = this.shipmentNo
      var _that = this
      if (num == null) {
        this.$modal.msgError("请填写发货单号!");
        return;
      }
      for (let i = 0; i < this.addGoodsList.length; i++) {
        if (this.addGoodsList[i].goodWarehouseList.length == 0) {
          this.$modal.msgError("请填写发货仓库!");
          return;
        }
      }
      ConfirmDeliveryQuantity(id).then(res => {
        if (res.code == 200) {
          this.$modal.confirm('是否确认此订单发货出库？').then(function () {
            updateSaleType(id, type, num).then(response => {
              if (response.code == 200) {
                _that.$modal.msgSuccess("发货成功");
                _that.close();
              }
            })
          })
        }
      })
    },
    //选择发货仓库按钮操作
    choiceWarehouse(row) {
      getWarehouse(row.id).then(response => {
        this.warehouseGoodsList = response.rows;
      })
      this.open = true;
      this.title = "选择发货仓库";
      this.loading = false
    },
    //添加商品发货仓库
    addGoodsDeliveryWarehouse() {
      var info = this.warehouseGoodsList
      let sale = this.sellId
      for (var i = 0; i < info.length; i++) {
        info[i].sellId = sale
      }
      let _that = this
      addGoodsSaleWarehouse(info).then(response => {
        if (response.code == 200) {
          _that.open = false
          _that.$modal.msgSuccess("添加成功!");
          _that.getList(sale)
        }
      })
    },
    //修改发货仓库按钮操作
    updateWarehouse(row) {
      let s = this.sellId;
      getWarehouseBySaleId(row.id, s).then(response => {
        this.updateWarehouseGoodsList = response.rows;
      })
      this.updateOpen = true;
      this.title = "修改发货仓库";
      this.loading = false
    },
    //修改商品发货仓库
    UGoodsSaleWarehouseNum() {
      let info = this.updateWarehouseGoodsList
      let sale = this.sellId
      let _that = this
      for (var i = 0; i < info.length; i++) {
        info[i].sellId = sale
      }
      checkGoodsSaleWarehouse(info).then(res => {
        if (res.code === 200) {
          upGoodsSaleWarehouse(info).then(response => {
            if (response.code == 200) {
              _that.updateOpen = false
              _that.$modal.msgSuccess("修改成功!");
              _that.getList(sale)
            }
          })
        }
      })
    },
    //商品总价计算
    handleEdit(index, row) {
      if (row.quantity && row.price) {
        row.oneGoodPrice = Number(row.quantity) * Number(row.price)
      }
    },
    //获取分类列表
    getCategoryList() {
      let params = {};
      listCategory(params).then(response => {
        this.categoryOptions = this.handleTree(response.data, "id", "parentId");
      });
    },
    //查询品牌列表
    getBrandList() {
      let params = {};
      listBrand(params).then(response => {
        this.brandList = response.rows;
      });
    },
    //获取客户信息
    getInfo(row) {
      const id = row
      getCustomer(id).then(response => {
        this.customerTelephone = response.data.phone
        this.detailedAdd = response.data.detailedAddress
        this.form.province = response.data.province
        this.form.city = response.data.city
        this.form.area = response.data.area
        this.form.detailedAddress = response.data.detailedAddress
        this.form.customerAddress = response.data.customerAddress
        this.selectedOptions = [response.data.province.toString(), response.data.city.toString(), response.data.area.toString()]
      });
    },
    //查询客户列表
    selectCustomer() {
      listCustomer().then(response => {
        this.customerList = response.rows;
      });
    },
    //elementUi选择地址
    handleChange(value) {
      this.selectedOptions = value
      var name = ''
      this.selectedOptions.map(item =>
        name += CodeToText[item] + '') //将省市区三个拼接一起
      this.form.province = value[0];
      this.form.city = value[1];
      this.form.area = value[2];
      this.form.customerAddress = name;
    },
    //展开行状态
    getRowClassName({row, rowIndex}) {
      if (row.goodWarehouseList.length == 0) {
        return 'row-expand-cover';
      }
    },
    //获取随机发货编号
    getCurrentTime() {
      //获取当前时间并打印
      var _this = this;
      let yy = new Date().getFullYear().toString();
      let mm = (new Date().getMonth() + 1).toString();
      let dd = new Date().getDate().toString();
      let hh = new Date().getHours().toString();
      let mf = (new Date().getMinutes() < 10 ? '0' + new Date().getMinutes() : new Date().getMinutes()).toString();
      let ss = (new Date().getSeconds() < 10 ? '0' + new Date().getSeconds() : new Date().getSeconds()).toString();
      _this.shipmentNo = "Hon" + yy + mm + dd + hh + mf + ss + Math.floor(Math.random() * 10000)
    },
    //商品小计
    getSummaries(param) {
      const {columns, data} = param;
      const sums = []; //声明变量
      columns.forEach((column, index) => {
        if (index === 0) {
          sums[index] = "小计";
          return;
        }
        const values = data.map((item) => Number(item[column.property]));
        if (
          column.property === "oneGoodPrice" ||
          column.property === "goodsNumber"
        ) {
          sums[index] = values.reduce((prev, curr) => {
            const value = Number(curr);
            if (!isNaN(value)) {
              return prev + curr;
            } else {
              return prev;
            }
          }, 0);
        } else {
          sums[index] = '';
        }
      });
      return sums;
    },
    //返回上一页商品列表页
    close() {
      this.$router.push({path: '/invoiceList'});
    },
  }
}

</script>
<style>
.row-expand-cover .el-table__expand-icon {
  visibility: hidden;
}
</style>
